local balancer = require "ngx.balancer"
local upstream = require "ngx.upstream"

local upstream_name = 'backend'

local cache = ngx.shared.cache

local serverCount = cache:get("serverCount")
ngx.log(ngx.DEBUG, "serverCount=" .. tostring(serverCount));

local key = "req_index"

local req_index = cache:get(key);
ngx.log(ngx.DEBUG, "req_index=" .. tostring(req_index));
--ngx.log(ngx.DEBUG, "0==nil=" .. tostring(not 0));

if not req_index or req_index == ngx.null or req_index >= serverCount then
    req_index = 0
    cache:set(key, req_index)
end

cache:incr(key, 1)

ngx.log(ngx.DEBUG, "req_index=" .. tostring(req_index));

local server = cache:get(req_index);

local index = string.find(server, ':')
local host = string.sub(server, 1, index - 1)
local port = string.sub(server, index + 1)

ngx.log(ngx.DEBUG, "host=" .. host);

balancer.set_current_peer(host, tonumber(port))